package com.lagou.sqlSession;

import com.lagou.pojo.Configuration;
import com.lagou.pojo.MapperStatement;

import java.lang.reflect.*;
import java.util.List;

public class DefaultSqlSession implements SqlSession {

    public DefaultSqlSession(Configuration configuration) {
        this.configuration = configuration;
    }

    private Configuration configuration;


    @Override
    public <E> List<E> selectList(String statementId, Object... params) throws Exception {
        SimpleExecutor simpleExecutor = new SimpleExecutor();
         MapperStatement mapperStatement = configuration.getMapperStatementMap().get(statementId);
        List<Object> list = simpleExecutor.query(configuration, mapperStatement, params);
        return (List<E>) list;
    }

    @Override
    public <T> T selectOne(String statementId, Object... params) throws Exception {
        List<Object> objects = selectList(statementId, params);
        if(objects.size()==1){
            return (T) objects.get(0);
        }else {
            throw new RuntimeException("查询结果为空或者查询结果过多");
        }
    }

    @Override
    public void executeTable(String statementId, Object... params) throws Exception {
        SimpleExecutor simpleExecutor = new SimpleExecutor();
        MapperStatement mapperStatement = configuration.getMapperStatementMap().get(statementId);
        simpleExecutor.query(configuration, mapperStatement, params);
    }

    @Override
    public <T> T getMapper(Class<?> mapperClass) {
        //使用jdk动态代理
        Object newProxyInstance = Proxy.newProxyInstance(DefaultSqlSession.class.getClassLoader(), new Class[]{mapperClass}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                String methodName = method.getName();
                String className = method.getDeclaringClass().getName();
                String statementId= className+"."+methodName;
                //准备参数2
                List<Object> list = selectList(statementId, args);
                //判断是否进行了泛型类型参数化
                Type genericReturnType = method.getGenericReturnType();
                if(genericReturnType instanceof ParameterizedType){
                 List<Object> objects =  selectList(statementId,args);
                 return objects;
                }
                return selectOne(statementId,args);
            }
        });
        return (T) newProxyInstance;
    }
}
